13. 函数剖析
函数剖析
你已经看过如何用 C++ 编写函数。一般而言,C++ 函数由函数声明和函数定义组成。
因为 C++ 是静态类型的,所以你需要指定函数输入变量的数据类型和函数返回的数据类型。
//function declaration
returndatatype functionname(datatype variable_a, datatype variable_b, etc.);
//function definition
returndatatype functionname(datatype variable_a, datatype variable_b, etc.) {
statement_1;
statement_2;
.... etc
return returndatatype
}
函数定义
SOLUTION:
因为该函数返回一个布尔值函数声明
SOLUTION:
该函数需要一个整数输入,并返回一个字符。小测试:编写函数
写一个名为 distance 的函数,该函数有 3 个输入和 1 个输出。输入为速度、加速度和时间。输出为随时间推移经过的距离。距离的计算公式为:
distance = velocity \times elapsedtime + 0.5 \times acceleration \times elapsedtime \times elapsedtime
本测验不评分。你会在 main() 函数中看到一些测试用例,用来测试你的代码。要运行你的代码,点击下面的“测试运行”按钮。
solution.cpp 中已经提供了一个参考答案,以便你和自己的结果相比较。
Start Quiz:
//TODO: include the iostream part of the standard library
//TODO: declare your function called distance
// Leave the main function as is
int main() {
// TODO: The following are examples you can use to test your code.
// You will need to uncomment them to get them working.
// std::cout << distance(3, 4, 5) << std::endl;
// std::cout << distance(7.0, 2.1, 5.4) << std::endl;
return 0;
}
//TODO: define your function
//TODO: include the iostream part of the standard library
#include <iostream>
//TODO: declare your function called distance
float distance(float velocity, float acceleration, float time_elapsed);
// Leave the main function as is
int main() {
// TODO: The following are examples you can use to test your code.
// You will need to uncomment them to get them working.
std::cout << distance(3, 4, 5) << std::endl;
std::cout << distance(7.0, 2.1, 5.4) << std::endl;
return 0;
}
//TODO: define your function
float distance(float velocity, float acceleration, float time_elapsed) {
return velocity*time_elapsed + 0.5*acceleration*time_elapsed*time_elapsed;
}